/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.util;

import com.comac.ins.common.core.exception.base.BaseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jep.SharedInterpreter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class IsfdAlgorithmConfigPythonExecute {

    public Map<String, Object> excute(String algorithmName, String implementation, String data) {
        try (SharedInterpreter jep = new SharedInterpreter()) {
            // 1. 执行代码，定义方法
            jep.exec(implementation);

            // 2. 解析输入数据为Map
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> params = objectMapper.readValue(data, new TypeReference<Map<String, Object>>() {
            });
            jep.set("params", params);

            // 3. 调用方法并获取结果
            jep.eval("result = " + algorithmName + "(params)");
            Map resultMap = jep.getValue("result", Map.class);

            // 4. 处理结果和错误
            if (resultMap == null) {
                throw new BaseException("Python方法未返回结果");
            }
            if (resultMap.containsKey("error")) {
                String error = (String) resultMap.get("error");
                log.error("Python错误: {}", error);
                throw new BaseException("Python执行错误: " + error);
            }
            return resultMap;
        } catch (Exception e) {
            log.error("执行失败: {}", e.getMessage(), e);
            throw new BaseException("执行失败: " + e.getMessage());
        }
    }
}
